package com.leetroll.media.job;

import com.google.gson.JsonObject;
import com.leetroll.api.service.ItemService;
import com.leetroll.common.entity.Item;
import com.leetroll.common.enums.EFileType;
import com.leetroll.common.enums.EItemType;
import com.leetroll.common.utils.FileUtils;
import com.leetroll.common.utils.JsonUtils;
import com.leetroll.media.service.UpDownloadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static com.leetroll.common.utils.FileUtils.*;

/**
 * poliigon网站的资源入库 （此服务后面放到别的模块）
 */
@Service
@Slf4j
public class Job_KitBash3D {

    private static final String ZIP_FILE_PATH = "F:\\resources\\3d_model\\KitBash3D\\original";
    private static final String TO_DB_FILE_PATH = "F:\\resources\\3d_model\\KitBash3D\\original";

    private static final ExecutorService executor = Executors.newFixedThreadPool(3);

    private final ItemService itemService;
    private final UpDownloadService upDownloadService;

    @Autowired
    public Job_KitBash3D(ItemService itemService, UpDownloadService upDownloadService) {
        this.itemService = itemService;
        this.upDownloadService = upDownloadService;
    }

    /**
     * 按文件格式打包成单独的zip (否则压缩包过大), 供用户选择文件格式单独下载
     */
    public static void zip() throws InterruptedException {
        File parent = new File(ZIP_FILE_PATH);
        if (!parent.exists() || !parent.isDirectory()) return;

        File[] docFolders = parent.listFiles();
        if (docFolders == null) return;

        for (File folder : docFolders) {
            if (folder.getName().equals("#seed") || folder.getName().equals("#finish") || folder.getName().equals("Aftermath"))
                continue; //跳过种子文件
            executor.submit(() -> zipItem(folder)
            );
        }
        Thread.sleep(1000L * 60 * 60 * 24 * 365);
        log.info("item 压缩完成");
    }

    private static void zipItem(File itemFolder) {
        log.info("----------------item start {}----------------", itemFolder.getName());
        File[] descFiles = itemFolder.listFiles();
        if (descFiles == null) return;
        for (File descFile : descFiles) {
            //待压缩的文件夹
            if (descFile.getName().equals(itemFolder.getName())) {
                File[] files = descFile.listFiles();
                if (files == null) continue;
                for (File file : files) {
                    if (file.getName().equals("Textures") || file.getName().endsWith("zip")) continue;
                    //将材质文件复制到待压缩的文件夹
                    copyFolder(descFile.getPath() + "\\Textures", file.getPath() + "\\Textures");
                    String path = descFile.getPath() + "\\" + file.getName() + ".zip";
                    toZip(file.getPath(), path);
                    //删除复制的文件
                    deleteFolder(new File(file.getPath() + "\\Textures"));
                }
            }
        }
        log.info("----------------item stop {}--------------", itemFolder.getName());
    }

    /**
     * 上传所有3d资源 (不包含附件文件)
     * # 1. 按文件名翻译, 入库
     * # 2. 按文件上传规范上传到阿里云
     */
    public void upload() throws InterruptedException {
        File folder = new File(TO_DB_FILE_PATH);
        if (!folder.exists() || !folder.isDirectory()) return;

        File[] docFolders = folder.listFiles();
        if (docFolders == null) return;

        for (File docFolder : docFolders) {
            executor.submit(() -> {
                        try {
                            uploadFile(docFolder);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
            );
        }
        Thread.sleep(1000L * 60 * 60 * 24 * 365);
        log.info("item 插入任务完成");
    }

    private void uploadFile(File docFolder) throws IOException {
        log.info("准备插入 item : {}", docFolder.getName());
        String jsonStr = FileUtils.getStr(new File(docFolder.getPath() + "\\info.json"));
        JsonObject json = JsonUtils.strToJson(jsonStr);
        String name = docFolder.getName();
        //插入item表
        Item item = new Item();
        item.setName(name);
        item.setAlias(name);
        item.setType(EItemType.MODEL.getType());
        item.setAuthor(json.get("author").getAsString());
        item.setPrice(json.get("price").getAsDouble());
        item.setCatId(7L);
        item.setStatus("show");
        item.setMark(json.get("mark").toString());
        item.setDesp(json.get("desp").getAsString());
        item.setCreateTime(new Date());
        item.setUpdateTime(new Date());
        itemService.save(item);

        File[] files = docFolder.listFiles();
        if (files == null) return;
        for (File file : files) {
            if (file.getName().equals("main")) {
                //插入主图文件
                File mainFile = Objects.requireNonNull(file.listFiles())[0];
                upDownloadService.upload2AliByType(item.getId(), mainFile, EFileType.MAIN);
            } else if (file.getName().equals("prev")) {
                //插入预览图文件
                for (File preFile : Objects.requireNonNull(file.listFiles())) {
                    upDownloadService.upload2AliByType(item.getId(), preFile, EFileType.PREVIEW);
                }
            }
        }
        log.info("--------------- item 插入成功 {} : {}", item.getId(), docFolder.getName());
    }

}
